import { ScrollView } from "@tarojs/components"
import { memo, useEffect, useState } from "react"

export interface VirtualListProps {
  data: any[]
  className?: string
  renderItem: (item: any, index: number) => React.ReactNode
  onReachBottom?: () => void
}

const PageVirtualList = ( props : VirtualListProps) => {
  const { data, renderItem, className, onReachBottom } = props
  const [ isLoading, setIsLoading ] = useState(false)
  
  useEffect(() => {
    setIsLoading(false)
  }, [data])

  useEffect(() => {
    if (isLoading) {
      setTimeout(() => {
        setIsLoading(false)
      }, 2000)
    }
  }, [isLoading])

  const onScrollToEnd = () => {
    console.log('onScrollToEnd')
    if (!isLoading) {
      setIsLoading(true)
      onReachBottom && onReachBottom()
    }
  }

  return (
    <ScrollView
      className={className}
      scrollY
      onScrollToLower={onScrollToEnd}
    >
      {data.map((item, index) => renderItem(item, index))}
    </ScrollView>
  )
}

export default memo(PageVirtualList)